<template>
  <div>
    <div v-if="departmentList.length" style="width: 317px;">
      <Tree
        :data="departmentList"
        :render="renderContent"
        class="demo-tree-render"
      ></Tree>
    </div>
  </div>
</template>
<script>
import { getDepartmentInfo, getDepartmentList } from "@/api/TApi/index.js";
import searchTree from "@riophae/vue-treeselect";
let pinyin = require("pinyin");
export default {
  components: { searchTree },
  data() {
    return {
      // 检验
      rules: {
        departmentName: {
          required: true,
          message: "请填写部门名称",
          trigger: "blur",
        },
        departmentType: {
          required: true,
          message: "请选择部门类型",
          trigger: "change",
        },
        departmentCompetency: {
          required: true,
          message: "请选择部门职能",
          type: "array",
          min: 1,
          trigger: "change",
        },
        departmentRole: {
          required: true,
          message: "请选择部门角色",
          type: "array",
          min: 1,
          trigger: "change",
        },
        defaultRole: {
          required: false,
          message: "请选择默认角色",
          type: "array",
          min: 1,
          trigger: "change",
        },
        diseases_ids: {
          required: true,
          message: "请选择默认病种",
          type: "array",
          min: 1,
          trigger: "change",
        },
      },
      department: "咨询",
      remarksloading: false,
      marketChanel: "市场来源渠道",
      defaultDisabled: false,
      firstDepartmentName: "",
      // 部门类型
      department_type: [
        {
          value: "1",
          label: "咨询",
        },
        {
          value: "2",
          label: "回访",
        },
        {
          value: "3",
          label: "运营",
        },
        {
          value: "4",
          label: "市场",
        },
      ],
      // 渠道
      source_channel: [],
      source_channels: [],

      // 部门职能
      competency: [],
      // 部门角色
      department_role: [],
      patient_diseases_role: [],
      // 默认角色
      default_role: [],
      roleList: [],
      addEdit: true,
      id: "",
      pid: "",
      fatherid: [], // 父级id
      // 表单
      form: {
        departmentName: "",
        departmentType: "",
        departmentSource: [],
        departmentCompetency: [],
        departmentRole: [],
        defaultRole: [],
        onlyTag: "",
        diseases_ids: [],
      },
      addModal: false,
      // 部门树组件列表数据
      departmentList: [],
      buttonProps: {
        type: "text",
        size: "small",
      },
      // 选中的数组
      select: [],
      source_channel: [],
      normalizer(node) {
        return {
          id: node.value,
          label: node.label,
          children: node.children,
        };
      },
      limitText: function(count) {
        return `+ ${count}`;
      },
    };
  },
  mounted() {
    this.init();
  },
  computed: {
    defaultRoleList() {
      let arr = [];
      this.form.departmentRole.forEach((e) => {
        this.department_role.forEach((v) => {
          if (v.value === e) {
            arr.push(v);
          }
        });
      });
      return arr;
    },
  },
  methods: {
    valueChange(e) {
      this.form.diseases_ids = [];
      e.forEach((item) => {
        let flag = true;
        this.patient_diseases_role.forEach((ele) => {
          if (ele.children && ele.children.length > 0) {
            if (ele.value == item) {
              flag = false;
              ele.children.forEach((id) => {
                this.form.diseases_ids.push(id.value);
              });
            }
          }
        });
        if (flag) {
          this.form.diseases_ids.push(item);
        }
      });
    },
    blurDepartment() {
      let nameArr = this.flatten(this.departmentList).map((ee) => {
        return ee.label;
      });
      let newArrLength = nameArr.filter((ee) => {
        return ee === this.form.departmentName;
      });
      let flag1 = pinyin(this.form.departmentName, {
        style: pinyin.STYLE_FIRST_LETTER,
      })
        .map((ee) => {
          return ee[0].toUpperCase();
        })
        .join("");
      let flag2 = pinyin(this.firstDepartmentName, {
        style: pinyin.STYLE_FIRST_LETTER,
      })
        .map((ee) => {
          return ee[0].toUpperCase();
        })
        .join("");
      this.form.onlyTag =
        flag2 + "-" + flag1 + (newArrLength.length ? newArrLength.length : "");
    },
    async init() {
      await this._getDepartmentList();
      await this._getDepartmentInfo();
    },
    changeRole(value) {
      // console.log(value,'value');
      // console.log(this.form.defaultRole,'this.form.defaultRole');
      // if (this.form.defaultRole.length) {
      //     this.form.defaultRole.forEach((vv) => {
      //         let flag = value.find((ees) => {
      //             return ees === vv;
      //     });
      //         if (!flag) {
      //             this.form.defaultRole = [];
      //         }
      //     });
      // }
      let arr = [];
      if (this.form.defaultRole.length) {
        this.form.defaultRole.forEach((vv) => {
          let cc = value.find((ees) => {
            return ees === vv;
          });
          arr.push(cc);
        });
      }
      this.form.defaultRole = arr;
    },
    _getDepartmentInfo() {
      if (
        this.departmentList[0].children &&
        this.departmentList[0].children.length > 0
      ) {
        this.$emit("changeId", this.departmentList[0].children[0].id);
        this.$emit("changePId", this.departmentList[0].children[0].pid);
        this.$set(this.departmentList[0].children[0], "selected", true);
      } else if (!this.departmentList[0].disabled) {
        this.$emit("changeId", this.departmentList[0].id);
        this.$emit("changePId", this.departmentList[0].pid);
        this.$set(this.departmentList[0], "selected", true);
      }
      // return new Promise((resolve) => {
      //   getDepartmentInfo({
      //     pid: 0,
      //   }).then((res) => {
      //     if (res.department_id === 0) {
      //       this.$emit("changeId", this.departmentList[0].children[0].id);
      //       this.$emit("changePId", this.departmentList[0].children[0].pid);
      //       this.$set(this.departmentList[0].children[0], 0, {
      //         selected: true,
      //         ...this.departmentList[0].children[0],
      //       });
      //     } else {
      //       this.$emit("changeId", res.department_id);
      //       this.treeArr(this.departmentList, res.department_id);
      //     }
      //     resolve();
      //   });
      // });
    },
    // 梳理树组件初始化被选中
    treeArr(arr, id) {
      // console.log(arr,'arr' ,id,'id');
      arr.forEach((e, index) => {
        if (e.id == id) {
          this.$set(e, "selected", true);
          this.$emit("changePId", e.pid);
        } else {
          if (e.children && e.children.length) {
            this.treeArr(e.children, id);
          }
        }
      });
    },
    flatten(arr) {
      return [].concat(
        ...arr.map((item) => {
          return [].concat(item, ...this.flatten(item.children));
        })
      );
    },
    // 处理数组
    handlerArr(arr) {
      arr.forEach((ee) => {
        ee.title = ee.label;
        ee.expand = true;
        ee.children && this.handlerArr(ee.children);
      });
      return arr;
    },
    // tree数据
    changeTree(select, val) {
      this.select = select;
      // console.log(this.select,'11');
      // this.select.forEach(item=>{
      //     if(item.pid==0){
      //         this.fatherid.push(item.id)
      //     }else{
      //         this.fatherid.push(item.pid)
      //         this.fatherid= [...new Set(this.fatherid)]
      //     }
      //     this.source_channel.push(item.value)
      // })
      // console.log(val,'11')
    },
    // 初始化新增或编辑下拉信息
    _getDepartmentList() {
      return new Promise((resolve) => {
        getDepartmentList().then((res) => {
          this.firstDepartmentName = res[0].label;
          let res1 = JSON.parse(JSON.stringify(res));
          this.$emit("changeList", res1);
          this.departmentList = this.handlerArr(res);
          this.departmentList[0].render = (h, { root, node, data }) => {
            return h(
              "span",
              {
                style: {
                  display: "flex",
                  width: "100%",
                  height: "100%",
                  justifyContent: "space-between",
                  alignItems: "center",
                  boxSize: "border-box",
                },
                on: {
                  click: () => {
                    this.changeDepartmentId(data);
                  },
                },
              },
              [
                h("span", [
                  h("span", data.title),
                  h(
                    "span",
                    {
                      style: {
                        marginLeft: "10px",
                      },
                    },
                    "(" + data.member_num + ")"
                  ),
                ]),
                h("span", {
                  style: {
                    display: "inline-block",
                    float: "right",
                    marginRight: "32px",
                  },
                }),
              ]
            );
          };
          resolve();
        });
      });
    },
    changeDepartmentId(data) {
      if (data.disabled) {
        return;
      }
      this.$emit("changeId", data.id);
      this.$emit("changePId", data.pid);
    },
    renderContent(h, { root, node, data }) {
      return h(
        "span",
        {
          style: {
            display: "flex",
            width: "100%",
            height: "100%",
            justifyContent: "space-between",
            alignItems: "center",
            paddingRight: "30px",
            boxSize: "border-box",
          },
          on: {
            click: () => {
              this.changeDepartmentId(data);
            },
          },
        },
        [
          h("span", [
            h("span", data.title),
            h(
              "span",
              {
                style: {
                  marginLeft: "10px",
                },
              },
              "(" + data.member_num + ")"
            ),
          ]),
        ]
      );
    },
  },
};
</script>
<style scoped>
/deep/.ivu-modal-body {
  padding: 5px 16px;
}
</style>
